package com.gemme.gemme.shequ;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.gemme.gemme.R;
import com.gemme.gemme.fragment.BaseLazyFragment;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.login.GlideCircleTransform;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.manager.DataPares;
import com.gemme.gemme.util.DpUtil;
import com.gemme.gemme.util.MobileUtil;
import com.gemme.gemme.util.SPUtil;
import com.gemme.gemme.util.StrUtil;
import com.gemme.gemme.view.StaggeredDividerItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by sp on 2019/7/18.
 * 首页
 */
public class Guangchang2Fragment extends BaseLazyFragment {

    View inflate;
    Context mContext;
    GcAdapter gcAdapter;
    RecyclerView mRecyclerView;
    SmartRefreshLayout mSmartRefreshLayout;

    private int pageIndex = 1;
    private int pageSize = 16;
    private List<CommunityBean.DataBean> gcDatas = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        inflate = inflater.inflate(R.layout.fragment_guangchang2, container, false);

        mContext = Guangchang2Fragment.this.getContext();

        initView(inflate);
        return inflate;
    }

    private void initView(View inflate) {
        mRecyclerView = inflate.findViewById(R.id.mRecyclerView);
        mSmartRefreshLayout = inflate.findViewById(R.id.mSmartRefreshLayout);
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        mRecyclerView.addItemDecoration(new StaggeredDividerItemDecoration(mContext, (int) getResources().getDimension(R.dimen.dp_11)));

        mSmartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                mSmartRefreshLayout.setEnableLoadMore(true);
                pageIndex = 1;
                getDatas();
            }

            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                pageIndex++;
                getDatas();
            }

        });
        mSmartRefreshLayout.autoRefresh();
    }

    @Override
    public void onLazyLoad() {
        getDatas();
    }

    @Override
    public void onResume() {
        super.onResume();
        getDatas();
    }

    private void getDatas() {
        String url = DataManager.BaseUrl + "community/appccontent/findCommunity?current=" + pageIndex + "&size=" + pageSize;

        /**
         * 去除tokenjjm
         */
//        HashMap<String, String> headMap = new HashMap<>();
//        headMap.put(DataManager.AuthorizationKey, DataManager.getToken(mContext));
        DataManager.toServer2(mContext, url, DataManager.GET_TYPE, "", null, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                mSmartRefreshLayout.finishRefresh();
                mSmartRefreshLayout.finishLoadMore();
                
                try {
                    CommunityBean communityBean = JSON.parseObject(response, CommunityBean.class);
                    List<CommunityBean.DataBean> datas = communityBean.getData();
                    
                    if (datas == null) {
                        return;
                    }

                    if (1 == pageIndex) {
                        gcDatas.clear();
                        gcDatas.addAll(datas);
                    } else {
                        gcDatas.addAll(datas);
                    }

                    if (gcAdapter == null) {
                        gcAdapter = new GcAdapter(gcDatas);
                        mRecyclerView.setAdapter(gcAdapter);
                    } else {
                        gcAdapter.setData(gcDatas);
                        gcAdapter.notifyDataSetChanged();
                    }

                    if (datas.size() < pageSize) {
                        mSmartRefreshLayout.setEnableLoadMore(false);
                    }

                } catch (Exception ex) {
                }
            }
        });
    }

    public class GcAdapter extends RecyclerView.Adapter<GcAdapter.ViewHolder> {

        private List<CommunityBean.DataBean> adapterList;

        public GcAdapter(List<CommunityBean.DataBean> adapterList) {

            this.adapterList = adapterList;
        }

        public void setData(List<CommunityBean.DataBean> data) {
            this.adapterList = data;
        }

        @NonNull
        @Override
        public GcAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(parent.getContext()).
                    inflate(R.layout.gc_item, null);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            inflate.setLayoutParams(layoutParams);
            return new GcAdapter.ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull GcAdapter.ViewHolder holder, int position) {
            try {

                setHeight(holder, position);
                CommunityBean.DataBean dataBean = adapterList.get(position);
                String type = dataBean.getType();  //1图片,2视频

                if ("1".equals(type)) {
                    String picturePath = dataBean.getPicturePath();
                    String[] split = picturePath.split(",");
                    if (split != null && split.length > 0) {
                        //添加图片圆角
                        RequestOptions options = new RequestOptions().bitmapTransform(new RoundedCorners(30));//图片圆角为30
                        Glide.with(mContext).load(split[0]) //图片地址
                                .apply(options)
                                .into(holder.picture);
                    }

                    holder.iv_video_label.setVisibility(View.GONE);
                } else {
                    holder.iv_video_label.setVisibility(View.VISIBLE);
                    String videoPath = dataBean.getVideoPath();

                    if (!TextUtils.isEmpty(videoPath)) {
                        Glide.with(mContext)
                                .setDefaultRequestOptions(
                                        new RequestOptions()
                                                .frame(1000000)
                                                .centerCrop()
                                )
                                .load(videoPath)
                                .into(holder.picture);
                    }
                }

                holder.tv_desc.setText(StrUtil.noNUll(dataBean.getLabel()) + "");
                String label = StrUtil.noNUll(dataBean.getLabel());
                if (TextUtils.isEmpty(label)) {
                    holder.tv_desc.setText(StrUtil.noNUll(dataBean.getCdescribe()) + "");
                }

                if (dataBean.getIsLike() == 1) {
                    holder.iv_dianzan.setBackgroundResource(R.drawable.pc_dianzan_select);
                } else {
                    holder.iv_dianzan.setBackgroundResource(R.drawable.pc_dianzan_shequ);
                }

                holder.tv_nickName.setText(MobileUtil.hideMiddleMobile(StrUtil.noNUll(dataBean.getNickName())) + "");
                holder.tv_link_count.setText(dataBean.getLikeCounts() + "");
                String headImg = dataBean.getHeadImg();
                if (!TextUtils.isEmpty(headImg)) {
                    Glide.with(mContext).load(StrUtil.noNUll(headImg)).transform(new GlideCircleTransform(mContext))
                            .into(holder.iv_head);
                }


                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int id = dataBean.getId();
                        if (id < 0) {
                            Toast.makeText(mContext, "暂无数据", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        Intent intent = new Intent(mContext, ShequDetailActivity.class);
                        intent.putExtra("data", id);
                        startActivity(intent);
                    }
                });

                holder.ll_dianzan.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (dataBean.getIsLike() == 1) {
                            cancelUserLike(dataBean);
                        } else {
                            dianzan(dataBean);
                        }
                    }
                });

            } catch (Exception e) {

            }
        }

        private void cancelUserLike(CommunityBean.DataBean dataBean) { //
            try {

                String contentId = dataBean.getId() + "";
                int likeUserId = dataBean.getUserId();

                String url = DataManager.BaseUrl + "community/appcuserslike/cancelUserLike?" +
                        "type=" + "1" +
                        "&contentId=" + contentId +
                        "&likeUserId=" + likeUserId +
                        "";


                HashMap<String, String> headMap = new HashMap<>();
                headMap.put(DataManager.AuthorizationKey, DataManager.getToken(mContext));
                DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("");

                        try {
                            if (DataPares.isSucess(mContext, response)) {
                                Toast.makeText(mContext, "取消成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(mContext, "取消失败", Toast.LENGTH_SHORT).show();
                            }
                            getDatas();
                        } catch (Exception e) {

                        }
                    }
                });
            } catch (Exception e) {

            }

        }

        private void dianzan(CommunityBean.DataBean dataBean) {
            try {

                String userId = SPUtil.getDataForString(mContext, Constant.UserId, "");
                String type = "1";
                String contentId = dataBean.getId() + "";
                int likeUserId = dataBean.getUserId();
/*
            String url = DataManager.BaseUrl + "community/appcuserslike/saveUserLike?" +
                    "userId=" + userId +
                    "&type=" + type +
                    "&contentId=" + contentId +
                    "&likeUserId=" + likeUserId +
                    "";
*/

                String url = DataManager.BaseUrl + "community/appcuserslike/saveUserLike?" +
                        "type=" + type +
                        "&contentId=" + contentId +
                        "&likeUserId=" + likeUserId +
                        "";


                HashMap<String, String> headMap = new HashMap<>();
                headMap.put(DataManager.AuthorizationKey, DataManager.getToken(mContext));
                DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("");

                        try {
                            if (DataPares.isSucess(mContext, response)) {
                                Toast.makeText(mContext, "点赞成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(mContext, "点赞失败", Toast.LENGTH_SHORT).show();
                            }
                            getDatas();
                        } catch (Exception e) {

                        }
                    }
                });
            } catch (Exception e) {

            }

        }


        private void setHeight(ViewHolder holder, int position) {
            try {
//                holder.picture;
                ViewGroup.LayoutParams layoutParams = holder.picture.getLayoutParams();
               /* if(position % 2 == 0){
//                    holder.picture.setMaxHeight(DpUtil.dip2px(mContext,200));
                    layoutParams.height = DpUtil.dip2px(mContext,240);
                    holder.picture.setLayoutParams(layoutParams);
                }else{
                    layoutParams.height = DpUtil.dip2px(mContext,180);
                    holder.picture.setLayoutParams(layoutParams);
                }*/

                if (position == 0) {
//                    holder.picture.setMaxHeight(DpUtil.dip2px(mContext,200));
                    layoutParams.height = DpUtil.dip2px(mContext, 160);
                    holder.picture.setLayoutParams(layoutParams);
                } else {
                    layoutParams.height = DpUtil.dip2px(mContext, 240);
                    holder.picture.setLayoutParams(layoutParams);
                }

                System.out.println("");
            } catch (Exception e) {

            }
        }

        @Override
        public int getItemCount() {
            return adapterList.size();
        }


        public class ViewHolder extends RecyclerView.ViewHolder {
            ImageView picture;
            ImageView iv_video_label;
            TextView tv_desc;
            ImageView iv_head;
            TextView tv_nickName;
            TextView tv_link_count;
            ImageView iv_dianzan;
            LinearLayout ll_dianzan;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);

                picture = itemView.findViewById(R.id.picture);
                iv_video_label = itemView.findViewById(R.id.iv_video_label);
                tv_desc = itemView.findViewById(R.id.tv_desc);
                iv_head = itemView.findViewById(R.id.iv_head);
                tv_nickName = itemView.findViewById(R.id.tv_nickName);
                tv_link_count = itemView.findViewById(R.id.tv_link_count);
                iv_dianzan = itemView.findViewById(R.id.iv_dianzan);
                ll_dianzan = itemView.findViewById(R.id.ll_dianzan);
            }
        }
    }


}